//////////////////////////////////////////////////////////////////////////////////////
//
//  Copyright (c) 2014-present, Egret Technology.
//  All rights reserved.
//  Redistribution and use in source and binary forms, with or without
//  modification, are permitted provided that the following conditions are met:
//
//     * Redistributions of source code must retain the above copyright
//       notice, this list of conditions and the following disclaimer.
//     * Redistributions in binary form must reproduce the above copyright
//       notice, this list of conditions and the following disclaimer in the
//       documentation and/or other materials provided with the distribution.
//     * Neither the name of the Egret nor the
//       names of its contributors may be used to endorse or promote products
//       derived from this software without specific prior written permission.
//
//  THIS SOFTWARE IS PROVIDED BY EGRET AND CONTRIBUTORS "AS IS" AND ANY EXPRESS
//  OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
//  OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
//  IN NO EVENT SHALL EGRET AND CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
//  INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
//  LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;LOSS OF USE, DATA,
//  OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
//  LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
//  NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
//  EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
//////////////////////////////////////////////////////////////////////////////////////

class Main extends eui.UILayer {

    public constructor(){
        super();
    }

    protected createChildren(): void {
        super.createChildren();

        egret.lifecycle.addLifecycleListener((context) => {
            // custom lifecycle plugin
        })

        egret.lifecycle.onPause = () => {
            egret.ticker.pause();
        }

        egret.lifecycle.onResume = () => {
            egret.ticker.resume();
        }

        //inject the custom material parser
        //注入自定义的素材解析器
        let assetAdapter = new AssetAdapter();
        egret.registerImplementation("eui.IAssetAdapter", assetAdapter);
        egret.registerImplementation("eui.IThemeAdapter", new ThemeAdapter());


        this.runGame().catch(e => {
            console.log(e);
        })
    }

    private async runGame() {
        // await this.loadResource()
        // this.createGameScene();
        // const result = await RES.getResAsync("description_json")
        // this.startAnimation(result);
        // await platform.login();
        // const userInfo = await platform.getUserInfo();

        var _gscreen = new turnplate();
        this.addChild(_gscreen);

        //this.createButtom();
        //this.testText();
        //this.testZindex();

        //this.testAddStage();

        //this.testTapCancle();

        //var _s:scale9gird = new scale9gird();
        //this.addChild(_s);

        //this.createTimer();
        //console.log(userInfo);

        // var _ticker = new testTicker();
        // this.addChild(_ticker)

        // var imgLoader:egret.ImageLoader = new egret.ImageLoader();
        // imgLoader.once( egret.Event.COMPLETE, this.imgLoadHandler, this ); 
        // imgLoader.load( "/resource/assets/Test/star.png" );

        // var _thttp = new testHttp();
        // this.addChild(_thttp);
    }

    // private onAddToStage( evt:egret.Event ) {
    //     var imgLoader:egret.ImageLoader = new egret.ImageLoader;
    //     imgLoader.once( egret.Event.COMPLETE, this.imgLoadHandler, this );
    //     imgLoader.load( "resource/dialog-bg.png" );
    // }

    // private _txInfo:egret.TextField;               /// 文本提示信息
    
    // private _bmpUIUse9:egret.Bitmap;
    // private _bmpUINouse9:egret.Bitmap;

    // private imgLoadHandler( evt:egret.Event ):void{
    //     var bmd:egret.BitmapData = evt.currentTarget.data;
    // }

    private createTimer(){
        var timer: egret.Timer = new egret.Timer(500,5);

        timer.addEventListener(egret.TimerEvent.TIMER, timerFunc, this);
        timer.addEventListener(egret.TimerEvent.TIMER_COMPLETE, timerComFunc, this);

        timer.start();

        function timerFunc(){
            console.log('1')
        }

        function timerComFunc(){
            console.log('2')
        }
    }

    private createButtom() {
        var _myButton: MyButton = new MyButton( 50, 50 );
        this.addChild( _myButton );

        var offsetX: number;
        var offsetY: number;
        var draggedObject:egret.Shape;

        _myButton.touchEnabled = true;
        _myButton.addEventListener(egret.TouchEvent.TOUCH_BEGIN,startMove,this);
        _myButton.addEventListener(egret.TouchEvent.TOUCH_END,stopMove,this);

        function startMove(e:egret.TouchEvent):void {
            draggedObject = e.currentTarget;

            offsetX = e.stageX - draggedObject.x;
            offsetY = e.stageY - draggedObject.y;

            this.addChild(draggedObject);
            this.stage.addEventListener( egret.TouchEvent.TOUCH_MOVE, onMove, this)
        }

        function stopMove(e: egret.TouchEvent){
            this.stage.removeEventListener(egret.TouchEvent.TOUCH_MOVE,onMove,this)
        }

        function onMove(e:egret.TouchEvent):void{
            draggedObject.x = e.stageX - offsetX;
            draggedObject.y = e.stageY - offsetY;
        }
    }

    private testText() {
        var bigText: egret.TextField = new egret.TextField();
        bigText.text = "少时诵诗书所所所所所所所所所所所所所所所所所所所所所所所所所所所";
        bigText.scrollRect = new egret.Rectangle(0,0,200,50);
        bigText.cacheAsBitmap = true;
        this.addChild(bigText);

        var btnLeft: egret.Shape = new egret.Shape();
        btnLeft.graphics.beginFill(0xcccc01);
        btnLeft.graphics.drawRect(0,0,50,50);
        btnLeft.graphics.endFill();
        btnLeft.x = 50;
        btnLeft.y = 100;
        this.addChild(btnLeft);
        btnLeft.touchEnabled = true;
        btnLeft.addEventListener(egret.TouchEvent.TOUCH_TAP,onScoll,this);

        var btnRight: egret.Shape = new egret.Shape();
        btnRight.graphics.beginFill(0x01cccc);
        btnRight.graphics.drawRect(0,0,50,50);
        btnRight.graphics.endFill();
        btnRight.x = 150;
        btnRight.y = 100;
        this.addChild(btnRight);
        btnRight.touchEnabled = true;
        btnRight.addEventListener(egret.TouchEvent.TOUCH_TAP,onScoll,this);

        function onScoll( e:egret.TouchEvent ):void {
            //var rect: egret.Rectangle = bigText.scrollRect;
            switch( e.$currentTarget ) {
                case btnLeft: 
                    bigText.scrollRect.x += 20;
                    break;
                case btnRight:
                    bigText.scrollRect.x -= 20;
                    break;
            } 
            //bigText.scrollRect = rect;
        }
    }

    private testZindex(){
        var sprcon: egret.Sprite = new egret.Sprite();
        this.addChild( sprcon );

        sprcon.x = 10;

        var sprNew: egret.Sprite = new egret.Sprite();
        sprNew.graphics.beginFill( 0xff0000 );
        sprNew.graphics.drawRect(0,0,300,150);
        sprNew.graphics.endFill();
        sprNew.x = 10;
        sprNew.y = 50;
        sprcon.addChildAt( sprNew, 1 );

        var sprArr: any[] = new Array();

        for(var i = 0 ; i < 4; i++){
            var spr: egret.Sprite = new egret.Sprite();
            spr.graphics.beginFill( 0xffffff * Math.random() );
            spr.graphics.drawRect( 0,0,100,100 );
            spr.graphics.endFill();
            spr.x = i * 20;

            sprArr.push( spr );
            sprcon.addChild( spr );
        }

        sprNew.touchEnabled = true;
        sprNew.addEventListener( egret.TouchEvent.TOUCH_TAP, changeZindex, this )

        function changeZindex(){
            sprcon.swapChildren( sprNew , sprArr[3]);
        }
    }

    private testAddStage() {
        this.addEventListener( egret.Event.ADDED_TO_STAGE, this.onAddStage, this)
    }

    private testTapCancle() {
        var scroller = new eui.Scroller();
        var list = new eui.List();
        list.itemRendererSkinName = `<e:Skin states="up,down,disabled" minHeight="50" minWidth="100" xmlns:e="http://ns.egret.com/eui"> <e:Image width="100%" height="100%" scale9Grid="1,3,8,8" alpha.disabled="0.5"
                            source="resource/assets/Button/button_up.png"
                            source.down="resource/assets/Button/button_down.png"/> <e:Label text="{data}" top="8" bottom="8" left="8" right="8"
                            textColor="0xFFFFFF" verticalAlign="middle" textAlign="center"/> </e:Skin>`
        var ac = new eui.ArrayCollection([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]);
        list.dataProvider = ac;
        scroller.viewport = list;
        scroller.height = 200;
        this.addChild(scroller);
        scroller.addEventListener(egret.TouchEvent.TOUCH_BEGIN,()=>{console.log("111 Scroller Begin")},this);
        list.addEventListener(egret.TouchEvent.TOUCH_BEGIN,()=>{console.log("111 List Begin")},this);
        scroller.addEventListener(egret.TouchEvent.TOUCH_END,()=>{console.log("222 Scroller END")},this);
        list.addEventListener(egret.TouchEvent.TOUCH_END,()=>{console.log("222 List END")},this);
        scroller.addEventListener(egret.TouchEvent.TOUCH_TAP,()=>{console.log("33 Scroller Tap")},this);
        list.addEventListener(egret.TouchEvent.TOUCH_TAP,()=>{console.log("33 List Tap")},this);
        scroller.addEventListener(egret.TouchEvent.TOUCH_CANCEL,()=>{console.log("44 Scroller cancel")},this);
        list.addEventListener(egret.TouchEvent.TOUCH_CANCEL,()=>{console.log("44 List cancel")},this);
    }

    private onAddStage( event: egret.Event ) {
        this.drawText();

        var spr1: egret.Sprite = new egret.Sprite();
        spr1.graphics.beginFill( 0x00f00, 1);
        spr1.graphics.drawRect(0,0,100,80);
        spr1.graphics.endFill();

        spr1.width = 100;
        spr1.height = 80;
        this.addChild(spr1);
        spr1.touchEnabled = true;

        spr1.addEventListener( egret.TouchEvent.TOUCH_TAP,this.onTouch, this);
        this.addEventListener( egret.TouchEvent.TOUCH_TAP,this.onTouchTap, this);
        this.addEventListener( egret.TouchEvent.TOUCH_TAP,this.onTouchTaps, this , true);
    }

    private txt: egret.TextField;
    
    private drawText(): void {

        console.log('11111'); 
        this.txt = new egret.TextField();
        this.txt.size = 24;
        this.txt.x = 250;
        this.txt.width = 200;
        this.txt.height = 200;
        this.txt.text = "事件文字";
        this.addChild( this.txt );
    }

     private onTouch( evt:egret.TouchEvent )
    {
        this.txt.text += "\n点击了spr1";
    }
    private onTouchTap( evt:egret.TouchEvent )
    {
        this.txt.text += "\n容器冒泡侦听\n---------";
    }
    private onTouchTaps( evt:egret.TouchEvent )
    {
        this.txt.text += "\n容器捕获侦听";
    }
    
    private async loadResource() {
        try {
            const loadingView = new LoadingUI();
            this.stage.addChild(loadingView);
            await RES.loadConfig("resource/default.res.json", "resource/");
            await this.loadTheme();
            await RES.loadGroup("preload", 0, loadingView);
            this.stage.removeChild(loadingView);
        }
        catch (e) {
            console.error(e);
        }
    }

    private loadTheme() {
        return new Promise((resolve, reject) => {
            // load skin theme configuration file, you can manually modify the file. And replace the default skin.
            //加载皮肤主题配置文件,可以手动修改这个文件。替换默认皮肤。
            let theme = new eui.Theme("resource/default.thm.json", this.stage);
            theme.addEventListener(eui.UIEvent.COMPLETE, () => {
                resolve();
            }, this);

        })
    }

    private textfield: egret.TextField;
    /**
     * 创建场景界面
     * Create scene interface
     */
    protected createGameScene(): void {
        let sky = this.createBitmapByName("bg_jpg");
        this.addChild(sky);
        let stageW = this.stage.stageWidth;
        let stageH = this.stage.stageHeight;
        sky.width = stageW;
        sky.height = stageH;

        let topMask = new egret.Shape();
        topMask.graphics.beginFill(0x000000, 0.5);
        topMask.graphics.drawRect(0, 0, stageW, 172);
        topMask.graphics.endFill();
        topMask.y = 33;
        this.addChild(topMask);

        let icon: egret.Bitmap = this.createBitmapByName("egret_icon_png");
        this.addChild(icon);
        icon.x = 26;
        icon.y = 33;

        let line = new egret.Shape();
        line.graphics.lineStyle(2, 0xffffff);
        line.graphics.moveTo(0, 0);
        line.graphics.lineTo(0, 117);
        line.graphics.endFill();
        line.x = 172;
        line.y = 61;
        this.addChild(line);


        let colorLabel = new egret.TextField();
        colorLabel.textColor = 0xffffff;
        colorLabel.width = stageW - 172;
        colorLabel.textAlign = "center";
        colorLabel.text = "Hello Egret";
        colorLabel.size = 24;
        colorLabel.x = 172;
        colorLabel.y = 80;
        this.addChild(colorLabel);

        let textfield = new egret.TextField();
        this.addChild(textfield);
        textfield.alpha = 0;
        textfield.width = stageW - 172;
        textfield.textAlign = egret.HorizontalAlign.CENTER;
        textfield.size = 24;
        textfield.textColor = 0xffffff;
        textfield.x = 172;
        textfield.y = 135;
        this.textfield = textfield;

        let button = new eui.Button();
        button.label = "Click!";
        button.horizontalCenter = 0;
        button.verticalCenter = 0;
        this.addChild(button);
        button.addEventListener(egret.TouchEvent.TOUCH_TAP, this.onButtonClick, this);
    }
    /**
     * 根据name关键字创建一个Bitmap对象。name属性请参考resources/resource.json配置文件的内容。
     * Create a Bitmap object according to name keyword.As for the property of name please refer to the configuration file of resources/resource.json.
     */
    private createBitmapByName(name: string): egret.Bitmap {
        let result = new egret.Bitmap();
        let texture: egret.Texture = RES.getRes(name);
        result.texture = texture;
        return result;
    }
    /**
     * 描述文件加载成功，开始播放动画
     * Description file loading is successful, start to play the animation
     */
    private startAnimation(result: Array<any>): void {
        let parser = new egret.HtmlTextParser();

        let textflowArr = result.map(text => parser.parse(text));
        let textfield = this.textfield;
        let count = -1;
        let change = () => {
            count++;
            if (count >= textflowArr.length) {
                count = 0;
            }
            let textFlow = textflowArr[count];

            // 切换描述内容
            // Switch to described content
            textfield.textFlow = textFlow;
            let tw = egret.Tween.get(textfield);
            tw.to({ "alpha": 1 }, 200);
            tw.wait(2000);
            tw.to({ "alpha": 0 }, 200);
            tw.call(change, this);
        };

        change();
    }

    /**
     * 点击按钮
     * Click the button
     */
    private onButtonClick(e: egret.TouchEvent) {
        let panel = new eui.Panel();
        panel.title = "Title";
        panel.horizontalCenter = 0;
        panel.verticalCenter = 0;
        this.addChild(panel);
    }
}
